package com.xiang.xoa;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

/**
 * @author drakeet
 */
public class SwipeBackDelegate implements SwipeBackLayout.SwipeBackListener {

    private SwipeBackLayout swipeBackLayout;
    private ImageView shadow;


    public void attach(Activity activity, int layoutResID) {
        View root = getContainer(activity);
        View view = LayoutInflater.from(activity).inflate(layoutResID, null);
        swipeBackLayout.addView(view);
        activity.setContentView(root);
    }

    public void attach(Fragment fragment, int layoutResID) {
        Activity activity = fragment.getActivity();
        View root = getContainer(activity);
        View view = LayoutInflater.from(fragment.getActivity()).inflate(layoutResID, null);
        swipeBackLayout.addView(view);
        activity.setContentView(root);
    }


    @SuppressWarnings("deprecation") private View getContainer(Context context) {
        RelativeLayout container = new RelativeLayout(context);
        swipeBackLayout = new SwipeBackLayout(context);
        swipeBackLayout.setOnSwipeBackListener(this);
        shadow = new ImageView(context);
        shadow.setBackgroundColor(context.getResources().getColor(R.color.black_p50));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
        container.addView(shadow, params);
        container.addView(swipeBackLayout);
        return container;
    }


    public void setDragEdge(SwipeBackLayout.DragEdge dragEdge) {
        swipeBackLayout.setDragEdge(dragEdge);
    }


    @Override
    public void onViewPositionChanged(float fractionAnchor, float fractionScreen) {
        shadow.setAlpha(1 - fractionScreen);
    }


    public void setSwipeBackEnabled(boolean enabled) {
        swipeBackLayout.setSwipeBackEnabled(enabled);
    }
}
